import PuzzleGame from './puzzle.js';

export default class GamePage {
  constructor(canvas, context) {
    this.canvas = canvas;
    this.ctx = context;
    this.game = null;
    this.isActive = false;

    // 添加按钮状态记录
    this.startButton = null;
    this.difficultyButtons = [];

    // 屏幕尺寸
    this.screenWidth = canvas.width;
    this.screenHeight = canvas.height;

    // 考虑导航栏高度
    this.navigationBarHeight = 44;

    // 像素比
    this.pixelRatio = 1;
    try {
      const systemInfo = wx.getSystemInfoSync();
      this.pixelRatio = systemInfo.pixelRatio || 1;
    } catch (e) {
      console.warn('获取像素比失败:', e);
    }

    // 颜色主题
    this.colors = {
      primary: '#6366F1',
      primaryDark: '#4F46E5',
      secondary: '#10B981',
      secondaryDark: '#059669',
      accent: '#F59E0B',
      background: '#F8FAFC',
      surface: '#FFFFFF',
      text: '#1E293B',
      textLight: '#64748B',
      border: '#E2E8F0',
      shadow: 'rgba(0, 0, 0, 0.1)'
    };

    // 添加体力更新回调
    if (this.game) {
      this.game.onEnergyUpdated = () => {
        this.showStartMenu(); // 刷新菜单显示
      };
    }
  }

  // 页面初始化
  init() {
    console.log('游戏页面初始化');

    // 创建游戏实例
    this.game = new PuzzleGame(this.canvas, this.ctx);

    // 设置回调
    this.game.onBackToMenu = () => {
      this.backToMenu();
    };

    // 加载资源
    this.loadResources();

    // 绑定事件
    this.bindEvents();
  }

  // 加载图片资源
  loadResources() {
    console.log('开始加载资源...');

    const image = wx.createImage();
    image.src = 'images/puzzle.jpg';

    image.onload = () => {
      console.log('图片加载成功');
      this.game.setImage(image);
      this.showStartMenu();
    };

    image.onerror = (err) => {
      console.error('图片加载失败:', err);
      this.createDefaultPuzzle();
    };
  }

  // 创建默认拼图（备用）
  createDefaultPuzzle() {
    console.log('创建默认拼图');

    const tempCanvas = wx.createCanvas();
    const tempCtx = tempCanvas.getContext('2d');
    tempCanvas.width = 300;
    tempCanvas.height = 300;

    // 禁用抗锯齿以获得清晰绘制
    tempCtx.imageSmoothingEnabled = false;

    // 绘制一个渐变色背景
    const gradient = tempCtx.createLinearGradient(0, 0, 300, 300);
    gradient.addColorStop(0, '#ff6b6b');
    gradient.addColorStop(0.5, '#4ecdc4');
    gradient.addColorStop(1, '#45b7d1');

    tempCtx.fillStyle = gradient;
    tempCtx.fillRect(0, 0, 300, 300);

    // 绘制一些图案 - 使用清晰字体
    tempCtx.fillStyle = 'white';
    tempCtx.font = 'bold 40px "Helvetica Neue", Arial, sans-serif';
    tempCtx.textAlign = 'center';
    tempCtx.textBaseline = 'middle';
    tempCtx.fillText('拼图', 150, 150);

    // 设置图片并显示菜单
    this.game.setImage(tempCanvas);
    this.showStartMenu();
  }

  // 显示开始菜单 - 美化版本
  showStartMenu() {
    console.log('显示开始菜单');

    // 清空画布
    this.ctx.clearRect(0, 0, this.screenWidth, this.screenHeight);

    // 设置高质量渲染
    this.ctx.imageSmoothingEnabled = false;

    // 绘制渐变背景
    this.drawMenuBackground();

    // 绘制体力显示
    this.drawEnergyDisplay();

    // 根据屏幕尺寸调整UI元素
    const titleFontSize = Math.max(28, Math.round(this.screenWidth * 0.07));
    const buttonFontSize = Math.max(18, Math.round(this.screenWidth * 0.048));
    const smallFontSize = Math.max(14, Math.round(this.screenWidth * 0.04));

    // 绘制标题
    this.drawTitle(titleFontSize);

    // 绘制预览图
    this.drawPreview(smallFontSize);

    // 绘制开始按钮
    this.drawStartButton(buttonFontSize);

    // 绘制难度选择
    this.drawDifficultySelector(buttonFontSize, smallFontSize);

    // 恢复图像平滑设置
    this.ctx.imageSmoothingEnabled = true;
  }

  drawMenuBackground() {
    // 创建渐变背景
    const gradient = this.ctx.createLinearGradient(0, 0, this.screenWidth, this.screenHeight);
    gradient.addColorStop(0, '#F0F9FF');
    gradient.addColorStop(0.5, '#EFF6FF');
    gradient.addColorStop(1, '#F8FAFC');

    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(0, 0, this.screenWidth, this.screenHeight);

    // 绘制装饰性背景元素
    this.drawBackgroundDecorations();
  }

  drawBackgroundDecorations() {
    // 绘制一些装饰性的圆形
    this.ctx.fillStyle = 'rgba(99, 102, 241, 0.03)';

    // 大圆
    this.ctx.beginPath();
    this.ctx.arc(this.screenWidth * 0.8, this.screenHeight * 0.2, 80, 0, Math.PI * 2);
    this.ctx.fill();

    // 中圆
    this.ctx.beginPath();
    this.ctx.arc(this.screenWidth * 0.1, this.screenHeight * 0.7, 50, 0, Math.PI * 2);
    this.ctx.fill();

    // 小圆
    this.ctx.beginPath();
    this.ctx.arc(this.screenWidth * 0.9, this.screenHeight * 0.8, 30, 0, Math.PI * 2);
    this.ctx.fill();
  }

  drawTitle(titleFontSize) {
    // 绘制主标题
    this.ctx.fillStyle = this.colors.text;
    this.ctx.font = `bold ${titleFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    const titleY = Math.round(this.navigationBarHeight + 80);

    // 标题阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.1)';
    this.ctx.shadowBlur = 4;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 2;

    this.ctx.fillText('益智拼图游戏', Math.round(this.screenWidth / 2), titleY);

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;

    // 绘制副标题
    const subtitleFontSize = Math.max(14, Math.round(this.screenWidth * 0.035));
    this.ctx.fillStyle = this.colors.textLight;
    this.ctx.font = `${subtitleFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.fillText('拖动拼图块完成挑战', Math.round(this.screenWidth / 2), titleY + 40);
  }

  drawPreview(smallFontSize) {
    const margin = 20;
    const previewSize = Math.min(220, Math.round(this.screenWidth - margin * 2));
    const previewX = Math.round((this.screenWidth - previewSize) / 2);
    const previewY = Math.round(this.navigationBarHeight + 150);

    // 绘制预览图容器 - 带阴影和圆角
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.15)';
    this.ctx.shadowBlur = 12;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;

    this.ctx.fillStyle = this.colors.surface;
    this.roundRect(this.ctx, previewX, previewY, previewSize, previewSize, 16);
    this.ctx.fill();

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;

    if (this.game.image) {
      // 在容器内绘制图片，留出边距
      const imagePadding = 8;
      const imageSize = previewSize - imagePadding * 2;
      const imageX = previewX + imagePadding;
      const imageY = previewY + imagePadding;

      // 绘制图片圆角遮罩
      this.ctx.save();
      this.roundRect(this.ctx, imageX, imageY, imageSize, imageSize, 12);
      this.ctx.clip();

      this.ctx.imageSmoothingEnabled = false;
      this.ctx.drawImage(
        this.game.image,
        0, 0, this.game.image.width, this.game.image.height,
        imageX, imageY, imageSize, imageSize
      );

      this.ctx.restore();
    }

    // 绘制预览标签
    this.ctx.fillStyle = this.colors.primary;
    this.ctx.font = `500 ${smallFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.fillText('预览', Math.round(this.screenWidth / 2), previewY + previewSize + 25);
  }

  drawStartButton(buttonFontSize) {
    const margin = 20;
    const buttonWidth = Math.min(260, Math.round(this.screenWidth - margin * 2));
    const buttonHeight = Math.max(50, Math.round(this.screenWidth * 0.12));
    const buttonX = Math.round((this.screenWidth - buttonWidth) / 2);
    const buttonY = Math.round(this.navigationBarHeight + 420);

    this.startButton = {
      x: buttonX,
      y: buttonY,
      width: buttonWidth,
      height: buttonHeight
    };

    // 绘制渐变按钮
    this.drawModernButton(
      buttonX, buttonY, buttonWidth, buttonHeight,
      '开始游戏',
      [this.colors.primary, this.colors.primaryDark],
      buttonFontSize,
      14
    );
  }

  drawDifficultySelector(buttonFontSize, smallFontSize) {
    const margin = 20;

    // 绘制选择难度标题
    this.ctx.fillStyle = this.colors.text;
    this.ctx.font = `600 ${buttonFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.fillText('选择难度', Math.round(this.screenWidth / 2), Math.round(this.navigationBarHeight + 510));

    const difficultyButtons = [{
        text: '3×3\n简单',
        size: 3,
        color: [this.colors.secondary, this.colors.secondaryDark]
      },
      {
        text: '4×4\n中等',
        size: 4,
        color: [this.colors.primary, this.colors.primaryDark]
      },
      {
        text: '5×5\n困难',
        size: 5,
        color: ['#EF4444', '#DC2626']
      }
    ];

    // 按钮尺寸和间距
    const buttonWidth = Math.min(85, Math.round((this.screenWidth - margin * 2) * 0.28));
    const buttonHeight = 65;
    const buttonSpacing = Math.max(12, Math.round(this.screenWidth * 0.03));
    const totalWidth = (buttonWidth * difficultyButtons.length) + (buttonSpacing * (difficultyButtons.length - 1));

    let currentX = Math.round((this.screenWidth - totalWidth) / 2);
    const buttonsY = Math.round(this.navigationBarHeight + 550);

    this.difficultyButtons = [];

    difficultyButtons.forEach(button => {
      const buttonInfo = {
        text: button.text,
        size: button.size,
        color: button.color,
        x: currentX,
        y: buttonsY,
        width: buttonWidth,
        height: buttonHeight
      };

      this.difficultyButtons.push(buttonInfo);

      // 绘制难度按钮
      const isSelected = button.size === this.game.gridSize;
      this.drawDifficultyButton(buttonInfo, isSelected, smallFontSize);

      currentX += buttonInfo.width + buttonSpacing;
    });
  }

  drawDifficultyButton(buttonInfo, isSelected, smallFontSize) {
    const radius = 12;

    // 绘制阴影
    this.ctx.shadowColor = isSelected ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.1)';
    this.ctx.shadowBlur = isSelected ? 15 : 8;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = isSelected ? 6 : 3;

    // 绘制渐变背景
    const gradient = this.ctx.createLinearGradient(
      buttonInfo.x, buttonInfo.y,
      buttonInfo.x, buttonInfo.y + buttonInfo.height
    );
    gradient.addColorStop(0, buttonInfo.color[0]);
    gradient.addColorStop(1, buttonInfo.color[1]);

    this.ctx.fillStyle = gradient;
    this.roundRect(this.ctx, buttonInfo.x, buttonInfo.y, buttonInfo.width, buttonInfo.height, radius);
    this.ctx.fill();

    // 如果被选中，绘制选中状态边框
    if (isSelected) {
      this.ctx.strokeStyle = '#FFFFFF';
      this.ctx.lineWidth = 3;
      this.roundRect(this.ctx, buttonInfo.x, buttonInfo.y, buttonInfo.width, buttonInfo.height, radius);
      this.ctx.stroke();
    }

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;

    // 绘制按钮文字
    this.ctx.fillStyle = '#FFFFFF';
    this.ctx.font = `bold ${smallFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    // 绘制多行文本
    const lines = buttonInfo.text.split('\n');
    lines.forEach((line, index) => {
      this.ctx.fillText(
        line,
        Math.round(buttonInfo.x + buttonInfo.width / 2),
        Math.round(buttonInfo.y + buttonInfo.height / 2 - (lines.length - 1) * 8 + index * 16)
      );
    });
  }

  drawModernButton(x, y, width, height, text, gradientColors, fontSize, radius = 12) {
    // 绘制阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.15)';
    this.ctx.shadowBlur = 12;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;

    // 绘制渐变背景
    const gradient = this.ctx.createLinearGradient(x, y, x, y + height);
    gradient.addColorStop(0, gradientColors[0]);
    gradient.addColorStop(1, gradientColors[1]);

    this.ctx.fillStyle = gradient;
    this.roundRect(this.ctx, x, y, width, height, radius);
    this.ctx.fill();

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;

    // 绘制按钮文字
    this.ctx.fillStyle = '#FFFFFF';
    this.ctx.font = `bold ${fontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    this.ctx.fillText(
      text,
      Math.round(x + width / 2),
      Math.round(y + height / 2)
    );
  }

  // 圆角矩形工具函数
  roundRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
  }

  // 绑定事件
  bindEvents() {
    console.log('绑定事件');

    // 移除之前可能绑定的事件
    this.unbindEvents();

    // 绑定新的触摸事件
    this.touchStartHandler = (e) => {
      if (!this.isActive) {
        this.handleMenuTouch(e.touches[0]);
      } else {
        this.game.onTouchStart(e.touches[0]);
      }
    };

    this.touchMoveHandler = (e) => {
      if (this.isActive) {
        this.game.onTouchMove(e.touches[0]);
      }
    };

    this.touchEndHandler = (e) => {
      if (this.isActive) {
        // 注意：触摸结束事件可能没有 touches，使用 changedTouches
        const touch = e.changedTouches ? e.changedTouches[0] : null;
        if (touch) {
          this.game.onTouchEnd(touch);
        }
      }
    };

    // 使用微信小游戏的触摸事件API
    wx.onTouchStart(this.touchStartHandler);
    wx.onTouchMove(this.touchMoveHandler);
    wx.onTouchEnd(this.touchEndHandler);
  }

  // 解绑事件（防止重复绑定）
  unbindEvents() {
    if (this.touchStartHandler) {
      wx.offTouchStart(this.touchStartHandler);
    }
    if (this.touchMoveHandler) {
      wx.offTouchMove(this.touchMoveHandler);
    }
    if (this.touchEndHandler) {
      wx.offTouchEnd(this.touchEndHandler);
    }
  }

  // 修改 gamePage.js 中的 handleMenuTouch 方法
  handleMenuTouch(touch) {
    if (!touch) return;

    const x = touch.clientX;
    const y = touch.clientY;

    console.log('菜单触摸位置:', x, y);

    // 检查体力显示区域点击
    if (this.energyDisplayArea &&
      x >= this.energyDisplayArea.x && x <= this.energyDisplayArea.x + this.energyDisplayArea.width &&
      y >= this.energyDisplayArea.y && y <= this.energyDisplayArea.y + this.energyDisplayArea.height) {
      console.log('点击体力显示区域');
      this.showEnergyDialog();
      return;
    }

    // 检查开始按钮
    if (this.startButton) {
      console.log('开始按钮区域:', this.startButton);
      if (x >= this.startButton.x && x <= this.startButton.x + this.startButton.width &&
        y >= this.startButton.y && y <= this.startButton.y + this.startButton.height) {
        console.log('点击开始按钮');

        // 检查体力
        if (this.game && this.game.energyManager && this.game.energyManager.getCurrentEnergy() === 0) {
          this.showNoEnergyDialog();
        } else {
          this.startGame();
        }
        return;
      }
    }

    // 检查难度选择按钮 - 修复这里的错误
    if (this.difficultyButtons && this.difficultyButtons.length > 0) {
      for (const button of this.difficultyButtons) {
        // 添加安全检查，确保 button 对象存在
        if (!button) continue;

        if (x >= button.x && x <= button.x + button.width &&
          y >= button.y && y <= button.y + button.height) { // 修复这里的拼写错误
          console.log('点击难度按钮:', button.size);

          // 检查体力
          if (this.game && this.game.energyManager && this.game.energyManager.getCurrentEnergy() === 0) {
            this.showNoEnergyDialog();
          } else {
            this.game.gridSize = button.size;
            // 重新计算布局
            this.game.calculateLayout();
            this.showStartMenu(); // 刷新菜单显示选中的难度
          }
          break;
        }
      }
    }
  }

  // 添加显示体力不足对话框的方法
  // showNoEnergyDialog2() {
  //   if (!this.game || !this.game.energyManager) return;

  //   const timeToNextRecovery = this.game.energyManager.getTimeToNextRecovery();
  //   const recoveryTime = this.game.energyManager.formatRecoveryTime(timeToNextRecovery);

  //   let content = '体力不足，无法开始游戏！';
  //   if (timeToNextRecovery > 0) {
  //     content += `\n${recoveryTime}后恢复1点体力`;
  //   }
  //   content += '\n观看广告可以立即获得体力。';

  //   wx.showModal({
  //     title: '体力不足',
  //     content: content,
  //     confirmText: '观看广告',
  //     cancelText: '取消',
  //     success: (res) => {
  //       if (res.confirm) {
  //         this.watchAdForEnergy();
  //       }
  //     }
  //   });
  // }

  // 修改 showNoEnergyDialog 方法
  showNoEnergyDialog() {
    if (!this.game || !this.game.energyManager) return;

    const timeToNextRecovery = this.game.energyManager.getTimeToNextRecovery();
    const recoveryTime = this.game.energyManager.formatRecoveryTime(timeToNextRecovery);

    let content = '体力不足，无法开始游戏！';
    if (timeToNextRecovery > 0) {
      content += `\n${recoveryTime}后自动恢复1点体力`;
    }
    content += '\n分享给好友可以立即获得体力。';

    wx.showModal({
      title: '体力不足',
      content: content,
      confirmText: '分享获取',
      cancelText: '观看广告',
      success: (res) => {
        if (res.confirm) {
          this.shareForEnergy();
        } else if (res.cancel) {
          this.watchAdForEnergy();
        }
      }
    });
  }

  // 确保 watchAdForEnergy 方法在获得体力后刷新菜单显示
  watchAdForEnergy() {
    if (!this.game || !this.game.energyManager) return;

    // 在实际应用中，这里应该调用微信广告API
    // 这里模拟广告回调
    console.log('模拟观看广告');

    // 模拟广告成功回调
    setTimeout(() => {
      this.game.energyManager.addEnergyFromAd(3);

      // 显示获得体力提示
      wx.showToast({
        title: `获得3点体力！`,
        icon: 'success',
        duration: 2000
      });

      // 刷新菜单显示
      this.showStartMenu();
    }, 1000);
  }

  // 开始游戏
  startGame() {
    console.log('开始游戏');
    this.isActive = true;

    // 确保游戏实例存在
    if (!this.game) {
      console.error('游戏实例不存在');
      return;
    }

    try {
      this.game.start();
      console.log('游戏开始成功');
    } catch (error) {
      console.error('游戏开始失败:', error);
      wx.showModal({
        title: '错误',
        content: '游戏启动失败，请重试',
        showCancel: false,
        confirmText: '确定'
      });
    }
  }

  // 返回菜单
  backToMenu() {
    console.log('返回菜单');
    this.isActive = false;
    this.showStartMenu();
  }

  // 页面显示
  show() {
    console.log('显示游戏页面');
    if (!this.isActive) {
      this.showStartMenu();
    } else {
      this.game.draw();
    }
  }

  // 页面隐藏
  hide() {
    console.log('隐藏游戏页面');
  }

  // 页面销毁
  destroy() {
    console.log('销毁游戏页面');
    this.unbindEvents();
    this.game = null;
  }

  drawEnergyDisplay() {
    if (!this.game || !this.game.energyManager) return;

    const energyManager = this.game.energyManager;
    const currentEnergy = energyManager.getCurrentEnergy();
    const maxEnergy = energyManager.maxEnergy;
    const timeToNextRecovery = energyManager.getTimeToNextRecovery();
    const recoveryProgress = energyManager.getRecoveryProgress();

    // 体力显示位置 - 左上角，与puzzle.js保持一致
    const energyWidth = Math.round(this.screenWidth * 0.16);
    const energyHeight = Math.round(40);
    const energyX = 20;
    const energyY = Math.round(this.navigationBarHeight + 20);

    // 记录体力显示区域，用于点击检测
    this.energyDisplayArea = {
      x: energyX,
      y: energyY,
      width: energyWidth,
      height: energyHeight
    };

    // 绘制垂直进度条背景
    const barWidth = 5;
    const barHeight = energyHeight - 12;
    const barX = energyX;
    const barY = energyY + 6;

    this.ctx.fillStyle = '#E2E8F0';
    this.roundRect(this.ctx, barX, barY, barWidth, barHeight, 3);
    this.ctx.fill();

    // 绘制垂直进度条前景（体力值）
    const energyPercent = energyManager.getEnergyPercent();
    const energyHeightFill = Math.max(4, barHeight * energyPercent);

    // 根据体力值改变颜色
    let energyColor;
    if (energyPercent > 0.6) {
      energyColor = '#10B981'; // 绿色
    } else if (energyPercent > 0.3) {
      energyColor = '#F59E0B'; // 黄色
    } else {
      energyColor = '#EF4444'; // 红色
    }

    this.ctx.fillStyle = energyColor;
    this.roundRect(this.ctx, barX, barY + barHeight - energyHeightFill, barWidth, energyHeightFill, 3);
    this.ctx.fill();

    // 绘制恢复进度条（如果体力未满）
    if (currentEnergy < maxEnergy && timeToNextRecovery > 0) {
      const recoveryHeightFill = Math.max(4, barHeight * recoveryProgress);

      this.ctx.fillStyle = 'rgba(99, 102, 241, 0.3)'; // 半透明蓝色
      this.roundRect(this.ctx, barX, barY + barHeight - recoveryHeightFill, barWidth, recoveryHeightFill, 3);
      this.ctx.fill();
    }

    // 绘制体力数值和恢复时间
    this.ctx.fillStyle = '#1E293B';
    this.ctx.font = '500 14px "Helvetica Neue", Arial, sans-serif';
    this.ctx.textAlign = 'left';

    // 体力数值
    this.ctx.fillText(
      `${currentEnergy}/${maxEnergy}`,
      energyX + barWidth + 8,
      energyY + 18
    );

    // 如果体力未满，显示恢复时间
    if (currentEnergy < maxEnergy && timeToNextRecovery > 0) {
      const recoveryTime = energyManager.formatRecoveryTime(timeToNextRecovery);
      const timeFontSize = 10;

      this.ctx.fillStyle = '#64748B';
      this.ctx.font = `${timeFontSize}px "Helvetica Neue", Arial, sans-serif`;

      this.ctx.fillText(
        recoveryTime,
        energyX + barWidth + 8,
        energyY + 35
      );
    }
  }

  // 修改 showEnergyDialog 方法
  showEnergyDialog() {
    if (!this.game || !this.game.energyManager) return;

    const energyManager = this.game.energyManager;
    const currentEnergy = energyManager.getCurrentEnergy();
    const maxEnergy = energyManager.maxEnergy;
    const timeToNextRecovery = energyManager.getTimeToNextRecovery();

    let content = `当前体力: ${currentEnergy}/${maxEnergy}`;

    if (currentEnergy < maxEnergy) {
      if (timeToNextRecovery > 0) {
        const recoveryTime = energyManager.formatRecoveryTime(timeToNextRecovery);
        content += `\n${recoveryTime}后恢复1点体力`;
      } else {
        content += '\n体力已恢复';
      }
    } else {
      content += '\n体力已满';
    }

    content += '\n\n获取更多体力方式：';
    content += '\n· 分享给好友 +1点';
    content += '\n· 观看广告 +3点';

    wx.showModal({
      title: '体力信息',
      content: content,
      confirmText: '分享获取',
      cancelText: '观看广告',
      confirmColor: '#10B981',
      cancelColor: '#F59E0B',
      success: (res) => {
        if (res.confirm) {
          this.shareForEnergy();
        } else if (res.cancel) {
          this.watchAdForEnergy();
        }
      }
    });
  }


  // 修改 shareForEnergy 方法
  shareForEnergy() {
    if (!this.game || !this.game.energyManager) return;

    // 调起分享
    wx.shareAppMessage({
      title: '这个拼图游戏超好玩！快来挑战你的大脑！🧩',
      imageUrl: 'images/share.png'
    });

    // 延迟5秒后获得体力
    setTimeout(() => {
      this.game.energyManager.addEnergyFromAd(1);
      wx.showToast({
        title: '获得1点体力！',
        icon: 'success',
        duration: 2000
      });

      // 刷新菜单显示
      this.showStartMenu();
    }, 5000);
  }
}